//
//  WMEAFNetworking.m
//  WMEMusic
//
//  Created by 恩叔 on 16/4/12.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEAFNetworking.h"

@implementation WMEAFNetworking
+ (void)GETNetWithUrl:(NSString *)url body:(id)body headerFile:(NSDictionary *)header response:(WMEResponseStyle)responseStyle success:(BlockOfSuccess)success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.设置请求头
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    //  3.设置返回数据的类型
    switch (responseStyle) {
        case WMEJOSN:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case WMEXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case WMEDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            NSLog(@"错误");
            break;
    }
    // 4.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    // 5.UTF-8转码
    //    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:url]];
    // 6.请求数据
    [manager GET:urlStr parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /****************************************************/
        //如果请求成功 , 回调请求到的数据 , 同时 在这里 做本地缓存
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        
        if (responseObject) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        if (error) {
            
            /*****************************************************/
            // 在这里读取本地缓存
            NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
            
            if (result) {
                success(result);
            } else {
                failure(error);
            }
        }
    }];
}

+ (void)POSTNetWithUrl:(NSString *)url body:(id)body bodyStyle:(WMEBodyRequestStyle)bodyRequestStyle headerFile:(NSDictionary *)header response:(WMEResponseStyle)responseStyle success:(BlockOfSuccess)success failure:(void (^)(NSError *))failure
{
    // 1.设置网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.设置Body体数据类型
    switch (bodyRequestStyle) {
        case WMERequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case WMERequestString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
                return parameters;
            }];
            break;
        default:
            break;
    }
    // 3.设置请求头
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    // 4.设置返回数据的类型
    switch (responseStyle) {
        case WMEJOSN:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case WMEXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case WMEDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            NSLog(@"错误");
            break;
    }
    // 5. 设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    // 6. UTF8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    // 7.请求数据
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /* ************************************************** */
        //如果请求成功 , 回调请求到的数据 , 同时 在这里 做本地缓存
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        
        if (responseObject) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            
            /*****************************************************/
            // 在这里读取本地缓存
            NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
            
            if (result) {
                success(result);
            } else {
                failure(error);
            }
            
        }
    }];
}
+ (void)getDataWithUrl:(NSString *)str completion:(void (^)(NSData *data))block
{
    NSString *urlStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    request.HTTPMethod = @"GET";
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 处理数据
        // 确定地址
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [NSString stringWithFormat:@"%@/%ld.xxoo", docPath, (unsigned long)[str hash]];
        
        
        if (data != nil) {
            [NSKeyedArchiver archiveRootObject:data toFile:path];
            // 当返回的数据不是空，就调用block
            block(data);
        } else {
            // 没有数据/请求失败 就从本地读取最近的一次成功数据
            NSData *pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (pickData != nil) {
                // 确保有数据才返回
                block(pickData);
            }
        }
    }];
}

@end
